<template>
  <div class="dynamic-container app-container">
    <CommonTable
      class="pagination-container"
      :columns="columns"
      :data-source="tableData"
      :options="options"
      :fetch="fetchTableData"
      :pagination="pagination"
      @row-click="handleRowClick"
      @selection-change="handleSelectionChange"
    />
    <el-dialog
      :title="formOptions.title"
      :visible.sync="formOptions.visible"
      width="50%"
      center
      @closed="closeDialog"
    >
      <el-form ref="formData" status-icon :rules="rules" :model="formData" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="动态名:" prop="dynamic_name">
              <el-input v-model="formData.dynamic_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号:" prop="phone">
              <el-input v-model="formData.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色:" prop="roles">
              <el-select v-model="formData.roles" placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.role_name"
                  :value="item.role_code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注:" prop="introduction">
              <el-input v-model="formData.introduction" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="头像:" prop="avatar">
              <!-- <el-input v-model="formData.avatar" /> -->
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="formData.avatar"
                  :src="formData.avatar"
                  class="avatar"
                >
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formOptions.visible = false">取 消</el-button>
        <el-button v-if="formOptions.type === 1" type="primary" @click="_handleAdd('formData')">新增</el-button>
        <el-button v-if="formOptions.type === 2" type="primary" @click="_handleEdit('formData')">修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '@/components/Table'
import { getList, getDynamicInfo, editDynamicInfo, delDynamic } from '@/api/dynamic'
export default {
  name: 'List',
  components: {
    CommonTable
  },
  data() {
    return {
      uploadUrl: 'http://127.0.0.1:7001/api/upload/uploadImage',
      roleOptions: [],
      formOptions: {
        visible: false,
        title: '',
        type: 1
      },
      columns: [
        {
          prop: 'id',
          label: '编号',
          width: 60
        },
        {
          prop: 'title',
          label: '动态标题',
          // render 可以根据你想要渲染的方式渲染
          // jsx 不提供 v-model 指令，若你想要使用，，推荐使用插件 babel-plugin-jsx-v-model
          // jsx https://github.com/vuejs/babel-plugin-transform-vue-jsx
          render: (row, index) => {
            return (
              <span style="'color: #ccc'" onClick={e => this.handleClick(e, row)}>
                {row.title}
              </span>
            )
          }
        },
        {
          prop: 'username',
          label: '微信用户'
        },
        {
          prop: 'desc',
          label: '动态描述'
        },
        {
          prop: 'created_at',
          label: '创建时间'
        },
        {
          button: true,
          label: '操作',
          group: [
            {
              // you can props => type size icon disabled plain
              name: '查看',
              type: 'primary',
              icon: 'el-icon-search',
              plain: true,
              onClick: (row, index) => {
                // 箭头函数写法的 this 代表 Vue 实例
                this.handleEditDialog(row, index)
              }
            },
            {
              name: '删除',
              type: 'danger',
              icon: 'el-icon-delete',
              disabled: false,
              onClick: (row) => {
                // 这种写法的 this 代表 group 里的对象
                this._handleDel(row)
                console.log(this)
                this.disabled = true
              }
            }
          ]
        }
      ],
      tableData: [],
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 15
      },
      options: {
        mutiSelect: true,
        index: true, // 显示序号， 多选则 mutiSelect
        loading: true, // 表格动画
        initTable: true // 是否一挂载就加载数据
      },
      rules: {
        user_name: [
          { required: true, message: '请输入动态名', trigger: 'blur' }
        ]
        // password: [
        //   { required: true, message: '请输入密码', trigger: 'blur' }
        // ]
      },
      formData: {
        user_name: '',
        introduction: '',
        phone: '',
        avatar: '',
        roles: ''
      }
    }
  },
  methods: {
    handleClick(e, row) {
      // transform-vue-jsx 的nativeOnClick 失效 , 所以采用 event.cancelBubble 控制点击事件的冒泡... 如果点击事件不影响你的点击行事件，可以不传
      e.cancelBubble = true // 停止冒泡，否则会触发 row-click
      console.log(row)
    },
    fetchTableData() {
      this.options.loading = true
      getList({
        current: this.pagination.pageIndex,
        size: this.pagination.pageSize
      })
        .then(res => {
          const { rows, count } = res.data
          this.tableData = rows
          this.pagination.total = count
          this.options.loading = false
        })
        .catch(error => {
          console.log(error)
          this.options.loading = false
        })
    },
    handleRowClick(row, event, column) {
      // 点击行的事件，同理可以绑定其他事件
      // console.log('click row:', row, event, column)
    },
    handleSelectionChange(selection) {
      console.log(selection)
    },
    async handleEditDialog(row, index) {
      this.resetForm('formData')
      this.formOptions.visible = true
      this.formOptions.title = '修改动态信息'
      this.formOptions.type = 2
      this.formData = {}
      const res = await getDynamicInfo({ dynamicid: row.dynamic_id })
      console.log(res)
      if (res.data) {
        this.formData = res.data.data
      }
    },
    _handleDel(row) {
      this.$confirm(`此操作将永久删除${row.dynamic_name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delDynamic({ id: row.dynamic_id })
        console.log(res)
        if (res) {
          this.$message({
            type: 'success',
            message: res.data.message
          })
          this.fetchTableData()
        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    _handleEdit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const res = await editDynamicInfo(this.formData)
          console.log(res)
          if (res.data) {
            this.$message.success(res.data.message)
            this.formOptions.visible = false
            this.fetchTableData()
          } else {
            this.$message.error(res.data.message)
          }
        } else {
          return false
        }
      })
    },
    closeDialog() {
      this.formData = {}
    },
    // 图片上传
    handleAvatarSuccess(res, file) {
      this.$set(this.formData, 'avatar', res.data.url)
    },
    // 图片上传
    beforeAvatarUpload(file) {
      console.log(file)
      const isType = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isType && isLt2M
    },
    resetForm(formName) {
      // console.log(formName);
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
